package com.ding.easycontroller.file.impl;

import com.ding.easycontroller.file.ScriptFilePathHolder;
import com.ding.easycontroller.file.WebSocketFile;
import com.ding.easycontroller.utils.ElementUtils;
import com.ding.easycontroller.work.WebSocket;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

@Component
public class WebSocketFileImpl implements WebSocketFile {


    @Autowired
    private XMLOutputter docWriter;

    private File root;

    WebSocketFileImpl(ScriptFilePathHolder holder) {
        File parent = holder.getRoot();
        File file = new File(parent, "websocket");
        if (!file.exists() && !file.mkdirs()) {
            throw new RuntimeException("路径创建失败" + file.getAbsolutePath());
        }
        this.root = file;
    }

    private Document websocket2Document(WebSocket websocket) {

        Document document = new Document();
        Element root = new Element("websocket");
        ScriptFile.scriptToElement(websocket, root);
        Element uri = new Element("uri");
        uri.setText(websocket.getUri());
        root.getChildren().add(uri);

        document.setRootElement(root);

        return document;
    }

    @Override
    public void add(WebSocket websocket) {

        try {
            Document document = websocket2Document(websocket);
            String strFromXml = docWriter.outputString(document);
            FileWriter writer = new FileWriter(new File(this.root, websocket.getId() + ".websocket"));
            writer.write(strFromXml);
            writer.close();

        } catch (Exception ignore) {

        }

    }

    /**
     * 从文件系统中将脚本文件移除
     */
    @Override
    public void removeById(String id) {
        if (!new File(this.root, id + ".websocket").delete()) {
            throw new RuntimeException("websocket移除失败" + id);
        }
    }

    @Override
    public List<WebSocket> listAll() {
        List<WebSocket> all = new ArrayList<>();
        File[] files = root.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(".websocket")) {
                    Element element = ElementUtils.readElement(file);
                    if (element != null && element.getName().equals("websocket")) {
                        WebSocket websocket = new WebSocket();
                        ScriptFile.elementToScript(element, websocket);
                        websocket.setUri(element.getChild("uri").getText());
                        websocket.setRate(Double.parseDouble(element.getChild("rate").getText()));
                        all.add(websocket);
                    }
                }
            }
        }
        return all;

    }

    @Override
    public void update(WebSocket websocket) {

        try {
            Document document = websocket2Document(websocket);
            String strFromXml = docWriter.outputString(document);
            FileWriter writer = new FileWriter(new File(this.root, websocket.getId() + ".websocket"));
            writer.write(strFromXml);
            writer.close();

        } catch (Exception ignore) {

        }

    }
}
